/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.starter.excel.handler;

import cn.idev.excel.context.AnalysisContext;
import jakarta.validation.ConstraintViolation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.starter.excel.annotation.ExcelLine;
import org.elsfs.cloud.starter.excel.kit.Validators;
import org.elsfs.cloud.starter.excel.vo.ErrorMessage;

/**
 * 默认的 AnalysisEventListener
 *
 * @author zeng
 */
@Slf4j
public class DefaultAnalysisEventListener extends ListAnalysisEventListener<Object> {

  private final List<Object> list = new ArrayList<>();

  private final List<ErrorMessage> errorMessageList = new ArrayList<>();

  private Long lineNum = 1L;

  @Override
  public void invoke(Object o, AnalysisContext analysisContext) {
    lineNum++;

    Set<ConstraintViolation<Object>> violations = Validators.validate(o);
    if (!violations.isEmpty()) {
      Set<String> messageSet =
          violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet());
      errorMessageList.add(new ErrorMessage(lineNum, messageSet));
    } else {
      Field[] fields = o.getClass().getDeclaredFields();
      for (Field field : fields) {
        if (field.isAnnotationPresent(ExcelLine.class) && field.getType() == Long.class) {
          try {
            field.setAccessible(true);
            field.set(o, lineNum);
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
      }
      list.add(o);
    }
  }

  @Override
  public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    LOGGER.debug("Excel read analysed");
  }

  @Override
  public List<Object> getList() {
    return list;
  }

  @Override
  public List<ErrorMessage> getErrors() {
    return errorMessageList;
  }
}
